package persist

import (
	"context"
	"github.com/olivere/elastic/v7"
	"log"
	"luiz/crawler/engine"
)

func ItemSaver(index string) chan engine.Item {
	client, err := elastic.NewClient(elastic.SetURL("http://124.71.171.6:9200/"))
	if err != nil {
		panic(err)
	}
	c := make(chan engine.Item)
	go func() {
		itemCount := 0
		for {
			house := <-c
			itemCount++
			err := Save(client, house, index)
			if err != nil {
				log.Printf("error:%v", err)
			}

		}
	}()
	return c
}
func Save(client *elastic.Client, item engine.Item, index string) (err error) {

	if item.Type == "" {
		return err
	}

	json := client.Index().
		Index(index).
		Type(item.Type).BodyJson(item)
	if item.Id != `` {
		json.Id(item.Id)
	}
	_, err = json.
		Do(context.Background())
	if err != nil {
		return err
	}
	return nil
}
